package com.lipuwater.agent.ui.activity.after;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ismartlib.ui.dialog.SheetDialog;
import com.ismartlib.utils.NetUtils;
import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.adapter.BaseViewHolder;
import com.lipuwater.agent.app.base.ui.BaseLayoutActivity;
import com.lipuwater.agent.ble.control.DeviceResetFilterControl;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsBasis;
import com.lipuwater.agent.http.bean.after.AfterDesBean;
import com.lipuwater.agent.http.bean.user.RoleConfig;
import com.lipuwater.agent.ui.activity.DeviceConnActivity;
import com.lipuwater.agent.ui.activity.PersonnelListActivity;
import com.lipuwater.agent.ui.activity.ReplaceFilterActivity;
import com.lipuwater.agent.ui.utils.BottomDialogUtils;
import com.lipuwater.agent.utils.MapToBeanUtil;
import com.lipuwater.agent.utils.onclick.NoDoubleClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.lipuwater.agent.R.id.layout_order_allot;


public class AfterActivity extends BaseLayoutActivity {

    @Bind(R.id.text_state)
    TextView textState;
    @Bind(R.id.text_user_name)
    TextView textUserName;
    @Bind(R.id.text_mobile_phone)
    TextView textMobilePhone;
    @Bind(R.id.text_model)
    TextView textModel;
    @Bind(R.id.text_model_code)
    TextView textModelCode;
    @Bind(R.id.text_des)
    TextView textDes;
    @Bind(R.id.text_address)
    TextView textAddress;
    @Bind(R.id.text_after_name)
    TextView textAfterName;
    @Bind(layout_order_allot)
    LinearLayout layoutOrderAllot;
    private int orderId;
    private AfterDesBean mAfterDesBean;
    private NoDoubleClick mNoDoubleClick = new NoDoubleClick();
    /**
     * 底部Dialog
     */
    private View mDialogView;
    private SheetDialog mSheetDialog;
    private BottomDialogUtils bottomDialogUtils;
    private List<String> menuList = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_after);
        toolbar.setBackgroundResource(R.drawable.img_title_bar);
        initTitle(R.drawable.icon_aleft_white, "售后单详情");
        toolbarTitle.setTextColor(Color.parseColor("#ffffff"));
        setTitleRight(R.drawable.icon_menu, null);
        layout_right.setVisibility(View.GONE);

        ButterKnife.bind(this);
        showLoading();
        orderId = getIntent().getIntExtra("orderId", 0);
        getAfterDes();
        setReloadClickListener();
    }

    @OnClick({R.id.layout_order_des, R.id.layout_settle_des, R.id.layout_right, layout_order_allot})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_order_des:
                if (mNoDoubleClick.check()) return;
                if (mAfterDesBean != null) {
                    Intent intent = new Intent(this, AfterFaultListActivity.class);
                    intent.putExtra("faultList", mAfterDesBean.getFaultInfo());
                    startActivity(intent);
                } else {
                    Toast("没有故障信息");
                }
                break;
            case R.id.layout_settle_des:
                if (mNoDoubleClick.check()) return;
                if (mAfterDesBean != null) {
                    Intent intent = new Intent(this, AfterSettleListActivity.class);
                    intent.putExtra("SettlementList", mAfterDesBean.getSettlementInfo());
                    startActivity(intent);
                } else {
                    Toast("没有订单信息");
                }
                break;
            case R.id.layout_right:
                if (mNoDoubleClick.check()) return;
                if (menuList == null) {
                    menuList = new ArrayList<>();
                    menuList.add("一键冲洗");
                    menuList.add("重置滤芯");
                    menuList.add("更换主板");
                    menuList.add("更换设备");
                }
                showMenuDialog(menuList);
                break;
            case R.id.layout_order_allot:
                if (mAfterDesBean != null && mAfterDesBean.getState() == 1) {
                    Toast("工单已完成");
                    return;//已经完成
                }
                Intent intent = new Intent(this, PersonnelListActivity.class);
                intent.putExtra("choose", true);
                intent.putExtra("chooseType", "after");
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case 101:
                    try {
                        String[] dataArray = data.getStringArrayExtra("data");
                        textAfterName.setText(dataArray[1]);
                        allotInstall(String.valueOf(orderId), dataArray[0]);
                    } catch (Exception e) {
                    }
                    break;
            }
        }
    }

    /**
     * 分配售后工单
     */
    private void allotInstall(String installId, String userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("workOrderId", installId);
        params.put("fulfiledBy", userId);
        ApiRequestsBasis.allotInstall(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    Toast("分配成功");
                } else {
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (NetUtils.isConnected(AfterActivity.this)) {
                    Toast(getString(R.string.service_error));
                } else {
                    Toast(getString(R.string.network_fails));
                }
            }
        });
    }

    private void getAfterDes() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("orderId", orderId);
        ApiRequestsBasis.getAfterDes(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    mAfterDesBean = (AfterDesBean) MapToBeanUtil.toJavaBean(result.getParams().get("salesInfo"), AfterDesBean.class);
                    setData(mAfterDesBean);
                } else {
                    layout_right.setVisibility(View.GONE);
                    showNoNetWork();
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                layout_right.setVisibility(View.GONE);
                showNoNetWork();
                if (NetUtils.isConnected(AfterActivity.this)) {
                    Toast(getString(R.string.service_error));
                } else {
                    Toast(getString(R.string.network_fails));
                }
            }
        });
    }

    private void setData(AfterDesBean afterDesBean) {
        if (afterDesBean != null) {
            textState.setText(afterDesBean.getStateString());
            textUserName.setText(afterDesBean.getClientName());
            textMobilePhone.setText(afterDesBean.getMobilePhone());
            textModel.setText(afterDesBean.getModelName());
            textModelCode.setText(afterDesBean.getModelCode());
            textDes.setText(afterDesBean.getDes());
            textAddress.setText(afterDesBean.getInstallAddress());
            if (roleType.equals(RoleConfig.MANAGER)) {
                layoutOrderAllot.setVisibility(View.VISIBLE);
                if (afterDesBean.getFulfiledBy() != null) {
                    textAfterName.setText(afterDesBean.getFulfiledBy());
                } else {
                    textAfterName.setText(userName);
                }
            }
            if(afterDesBean.getState()==1){
                layout_right.setVisibility(View.GONE);
            }else{
                layout_right.setVisibility(View.VISIBLE);
            }
            hideEmptyLayout();
        } else {
            layout_right.setVisibility(View.GONE);
            showNoNetWork();
        }
    }

    private void setReloadClickListener() {
        emptyLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoading();
                getAfterDes();
            }
        });
    }

    private void showMenuDialog(final List<String> mData) {
        if (bottomDialogUtils == null) {
            bottomDialogUtils = new BottomDialogUtils(this);
        }
        mDialogView = bottomDialogUtils.getView(mData);
        TextView textTitle = (TextView) mDialogView.findViewById(R.id.text_left);
        textTitle.setText("选择操作");
        bottomDialogUtils.onBindItemView(new BottomDialogUtils.ViewHolder() {
            @Override
            public void onBindViewHolder(BaseViewHolder holder, final int position) {
                final String itemStr = mData.get(position);
                holder.setText(R.id.text, itemStr);
                holder.getView(R.id.text).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mSheetDialog.dismiss();
                        switch (itemStr) {
                            case "一键冲洗":
                                new DeviceResetFilterControl(AfterActivity.this, mAfterDesBean.getMac(), 0, true);
                                break;
                            case "重置滤芯":
                                if (mAfterDesBean != null) {
                                    Intent intent = new Intent(AfterActivity.this, ReplaceFilterActivity.class);
                                    intent.putExtra("deviceName", mAfterDesBean.getDeviceName());
                                    intent.putExtra("mac", mAfterDesBean.getMac());
                                    intent.putExtra("filterState", mAfterDesBean.getFilterState());
                                    startActivity(intent);
                                }
                                break;
                            case "更换主板":
                                Intent intent1 = new Intent(AfterActivity.this, DeviceConnActivity.class);
                                intent1.putExtra("devId", mAfterDesBean.getId());
                                intent1.putExtra("installType", 2);
                                startActivity(intent1);
                                break;
                            case "更换设备":
                                Intent intent = new Intent(AfterActivity.this, DeviceConnActivity.class);
                                intent.putExtra("devId", mAfterDesBean.getId());
                                intent.putExtra("installType", 1);
                                startActivity(intent);
                                break;
                        }
                    }
                });
            }
        });
        mSheetDialog = new SheetDialog(this);
        mSheetDialog.setView(mDialogView);
        mSheetDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


}
